package com.longway.core.toolbox.wdp.api;

import java.util.Map;
import java.util.concurrent.Callable;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.longway.core.toolbox.utils.HttpUtils;
import com.longway.core.toolbox.utils.RetryUtils;
import com.longway.core.toolbox.wdp.WdpConfig;
import com.longway.core.toolbox.wdp.WdpConfigKit;

public class PreAuthCodeApi {
    private static String url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode";

    /**
     * 获取 PreAuthCode
     * @return PreAuthCode preAuthCode
     */
    public static PreAuthCode getPreAuthCode() {
    	WdpConfig wdp = WdpConfigKit.getWdpConfig();
    	PreAuthCode result = getPreAuthCode(wdp);
        return result;
    }
    
    /**
     * 直接获取 PreAuthCode 字符串，方便使用
     * @return String PreAuthCode
     */
    public static String getPreAuthCodeStr() {
        return getPreAuthCode().getPreAuthCode();
    }

    /**
     * 获取PreAuthCode
     * @param WdpConfig
     * @return PreAuthCode
     */
    private static PreAuthCode getPreAuthCode(WdpConfig wdp) {
        String appId = wdp.getAppId();
        String componentAccessToken = ComponentAccessTokenApi.getComponentAccessTokenStr();
        final Map<String, String> queryParas = Ret.create("component_appid", appId);
        // 最多三次请求
        PreAuthCode result = RetryUtils.retryOnException(3, new Callable<PreAuthCode>() {
        @Override
        public PreAuthCode call() throws Exception {
            String json = HttpUtils.post(url+"?component_access_token="+componentAccessToken, JsonKit.toJson(queryParas));
            return new PreAuthCode(json);
        }
        });
        return result;
    }

}
